import React, { Component } from 'react';
import { ImageBackground, TextInput, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import TabBarImage from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { statusBarHeight, titleHeight, width, unitWidth } from '../constants/AdapterUtil';
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
import { LeftComponent } from '../components/MyHeader';
import { SubmitButton6, SMButton, SDButton, AddShoppingCartButton } from '../components/Button';
import MyListView from '../components/MyListView';
import { DeleteTextView } from '../components/MyTextView';
import { Rating, AirbnbRating } from 'react-native-elements';
import NavigationService from '../constants/NavigationService';
import { postFetch } from '../constants/HttpExtension';
import { api_goods_get_list, api_merch_list_ajaxmerchuser } from '../constants/HttpServices';
import CommonUtil from '../constants/CommonUtil';

export default class SearchScreen extends Component {

    constructor(props) {
        super(props)
        this.state = {
            searchText: '',
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            if (this.refs.list1) {
                this.refs.list1.search();
            }
            if (this.refs.list2) {
                this.refs.list2.search();
            }
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.white }}>
                <View style={{ height: statusBarHeight + titleHeight, width: width, backgroundColor: Colors.white }}>
                    <View style={{ marginTop: statusBarHeight, height: titleHeight, width: width, backgroundColor: Colors.white, flexDirection: 'row', borderWidth: 0.5, borderBottomColor: Colors.colorE8, borderColor: Colors.transparent }}>
                        <View style={{ flex: 1, justifyContent: 'center' }}>
                            <LeftComponent leftClick={() => { this.props.navigation.pop(); }} leftImg={require('../res/ic_arrow_left.png')} />
                        </View>
                        <View style={{ flex: 5, alignItems: 'center', justifyContent: 'center' }}>
                            <View style={{ width: 250 * unitWidth, height: 29 * unitWidth, borderRadius: 20, backgroundColor: Colors.colorEF, flexDirection: 'row', alignItems: 'center', }}>
                                <Image source={require('../res/ic_search.png')}
                                    style={{ width: 13 * unitWidth, height: 14 * unitWidth, marginHorizontal: 10 * unitWidth }}
                                    resizeMode='stretch' />
                                <TextInput
                                    style={{ fontSize: 13, height: 35 * unitWidth, width: 250 * unitWidth }}
                                    onChangeText={this.onSearchTextChange.bind(this)}
                                    maxLength={20}
                                    placeholder='搜索'
                                    value={this.state.searchText}
                                />
                            </View>
                        </View>
                        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-end' }}>
                            <SubmitButton6 text='搜索' onPress={() => { this.doSearch() }} />
                        </View>
                    </View>
                </View>
                <View style={{ flex: 1 }}>
                    <ScrollableTabView
                        style={{ backgroundColor: Colors.white }}
                        tabBarUnderlineStyle={{ backgroundColor: Colors.transparent }}
                        tabBarActiveTextColor={Colors.colorRed}
                        tabBarInactiveTextColor={Colors.color99}
                        initialPage={0}
                        onChangeTab={(value) => {

                        }}
                        renderTabBar={() => <DefaultTabBar style={{
                            height: 50,
                            borderColor: Colors.transparent,
                        }} renderTab={
                            (name, page, isTabActive, onPressHandler, onLayoutHandler) => {
                                const { activeTextColor, inactiveTextColor, textStyle, } = this.props;
                                const textColor = isTabActive ? Colors.colorOrange : inactiveTextColor;
                                const fontWeight = isTabActive ? 'bold' : 'normal';
                                const fontSize = isTabActive ? 18 : 18;

                                return <TouchableOpacity
                                    style={{ flex: 1, }}
                                    key={name}
                                    onPress={() => onPressHandler(page)}>
                                    <View style={{
                                        flex: 1,
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        paddingBottom: 10,
                                    }}>
                                        <Text style={[{ color: textColor, fontWeight, fontSize: fontSize }, textStyle,]}>
                                            {name}
                                        </Text>
                                        {isTabActive ?
                                            <View style={{ width: 60 * unitWidth, height: 3 * unitWidth, backgroundColor: Colors.colorOrange, borderRadius: 15, position: 'absolute', bottom: 0 }} /> : null}
                                    </View>
                                </TouchableOpacity>;
                            }} />}>
                        <ProductListScreen ref='list1' tabLabel='产品' searchText={this.state.searchText} />
                        <BusinessListScreen ref='list2' tabLabel='服务商' searchText={this.state.searchText} />
                    </ScrollableTabView>
                </View>
            </View >
        )
    }

    onSearchTextChange(text) {
        this.setState({
            searchText: text
        }, () => {

        })
    }

    doSearch() {
        if (this.refs.list1) {
            this.refs.list1.search();
        }
        if (this.refs.list2) {
            this.refs.list2.search();
        }
    }
}

class ProductListScreen extends Component {
    constructor(props) {
        super(props)
        this.state = {
            list: [],
        }
    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    search() {
        this.refs.MyListView.onRefresh();
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF5 }}>
                <MyListView
                    ref='MyListView'
                    list={this.state.list}
                    numColumns={2}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                    canLoadMore={true}
                />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <View style={{ justifyContent: 'center', alignItems: 'center', width: width / 2, height: 230 * unitWidth }}>
                <TouchableOpacity style={{
                    width: 172 * unitWidth, height: 215 * unitWidth,
                    alignItems: 'center', backgroundColor: Colors.white, borderRadius: 7, paddingHorizontal: 2 * unitWidth
                }} activeOpacity={0.5} onPress={() => { NavigationService.navigate('GoodsDetail', { id: item.id }) }}>
                    <Image source={{ uri: item.thumb }}
                        style={{ width: 168 * unitWidth, height: 120 * unitWidth }}
                        resizeMode='cover' />
                    <Text style={{ fontWeight: 'bold', color: Colors.black, fontSize: 16, marginVertical: 4 * unitWidth }}>{item.title}</Text>
                    <View style={{ paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start' }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                    </View>
                    <View style={{ alignSelf: 'flex-start', marginTop: 5 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 172 * unitWidth }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                        <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                        <AddShoppingCartButton
                            style={{ position: 'absolute', right: 10 * unitWidth, }}
                            id={item.id} />
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    //获取商品列表
    getData(page) {
        let params = {
            page: page,
            keywords: this.props.searchText
        }
        postFetch(api_goods_get_list, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                    }, () => {
                        this.refs.MyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.MyListView.onHasMore();
                        })
                    } else {
                        this.refs.MyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}

class BusinessListScreen extends Component {
    constructor(props) {
        super(props)
        this.state = {
            list: [],
        }
    }

    componentDidMount() {
        this.getData(1);
    }

    componentWillUnmount() {

    }

    search() {
        this.refs.MyListView.onRefresh();
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF5 }}>
                <MyListView
                    ref='MyListView'
                    list={this.state.list}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                    canLoadMore={true}
                />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <TouchableOpacity style={{
                width: width,
                height: 145 * unitWidth,
                backgroundColor: Colors.white, justifyContent: 'center'
            }} activeOpacity={0.7} onPress={() => {
                NavigationService.navigate('ServiceProviderDetail', { merchid: item.id })
            }}>
                <View style={{
                    paddingHorizontal: 20 * unitWidth,
                    flexDirection: 'row', alignItems: 'center'
                }}>
                    <Image style={{ width: 115 * unitWidth, height: 90 * unitWidth }} source={{ uri: item.logo }} resizeMode='stretch' />
                    <View style={{ alignItems: 'flex-start', marginLeft: 7 * unitWidth }}>
                        <Text style={{ color: Colors.black, fontSize: 15 }}>{item.merchname}</Text>
                        <Rating
                            style={{ marginTop: 7 * unitWidth }}
                            readonly={true}
                            startingValue={item.score}
                            imageSize={20}
                        />
                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 7 * unitWidth }}>
                            <Image style={{ width: 13 * unitWidth, height: 16 * unitWidth }} source={require('../res/syss_dddw.png')} resizeMode='stretch' />
                            <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>{item.address}</Text>
                        </View>
                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 7 * unitWidth }}>
                            {item.is_realname > 0 ? <SMButton style={{}} id={item.id} /> : null}
                            {item.is_realname > 2 ? <SDButton style={{ marginLeft: 5 * unitWidth }} id={item.id} /> : null}
                        </View>
                    </View>
                    <TouchableOpacity style={{
                        alignSelf: 'flex-start', alignItems: 'center',
                        position: 'absolute', right: 15 * unitWidth,
                    }} activeOpacity={0.5}
                        onPress={() => {
                            if (item.isfollow == 1) {
                                CommonUtil.cancelfollow(item.id, {
                                    success: (response) => {
                                        this.refs.StickyListView._onRefresh();
                                    },
                                    fail: (response) => {

                                    }
                                })
                            } else if (item.isfollow == 0) {
                                CommonUtil.follow(item.id, {
                                    success: (response) => {
                                        this.refs.StickyListView._onRefresh();
                                    },
                                    fail: (response) => {

                                    }
                                })
                            }
                        }}>
                        <Image style={{ width: 18 * unitWidth, height: 16 * unitWidth }} source={item.isfollow == 1 ? require('../res/syss_guanzhu.png') : require('../res/syss_guanzhu2.png')} resizeMode='stretch' />
                        <Text style={{ color: Colors.color66, fontSize: 13, marginTop: 10 * unitWidth }}>关注</Text>
                    </TouchableOpacity>
                </View>
                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * unitWidth, marginHorizontal: 20 * unitWidth }}>
                    <Image style={{ width: 14 * unitWidth, height: 14 * unitWidth }} source={require('../res/syss_zyyw.png')} resizeMode='stretch' />
                    <Text style={{ color: Colors.color66, fontSize: 14, marginLeft: 5 * unitWidth }}>主营业务：{item.salecate}</Text>
                </View>
                {item.redpackid != '0' ?
                    <TouchableOpacity style={{ position: 'absolute', right: 15 * unitWidth, top: 70 * unitWidth }} activeOpacity={0.7}>
                        <Image style={{ width: 20 * unitWidth, height: 40 * unitWidth }} source={require('../res/syss_hongbao.png')} resizeMode='stretch' />
                    </TouchableOpacity> : null}
                {index == this.state.list.length - 1 ?
                    null : <View style={{ backgroundColor: Colors.colorE8, width: 338 * unitWidth, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                }
            </TouchableOpacity>
        )
    }

    getData(page) {
        let params = {
            page: page,
            lat: global.locationInfo.lat,
            lng: global.locationInfo.lng,
            sorttype: 0,
            keyword: this.props.searchText
        }
        postFetch(api_merch_list_ajaxmerchuser, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                    }, () => {
                        this.refs.MyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.MyListView.onHasMore();
                        })
                    } else {
                        this.refs.MyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}